package com.universityJob.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author mao on 2021/4/9.
 * @version 1.0 maozhijob@163.com
 */
@Component
public class Upload {
    @Value("${upload.file}")
    private String filePath;

    public R uploadFile( MultipartFile file,String fileName) {
        FileOutputStream out = null;
        try {
            File f = new File(filePath);
            if (!f.exists()) {
                f.mkdirs();// 不存在路径则进行创建
            }

            // 重新自定义文件的名称
            String filePaths = filePath + fileName;
            File fo = new File(filePaths);
            if (fo.exists()){
                fo.delete();
            }
            out = new FileOutputStream(filePaths);
            out.write(file.getBytes());
            out.flush();
            out.close();
            return R.ok().put("url",filePaths);
        } catch (Exception e) {
            return R.error("上传失败！");
        } finally {
            if (out != null) {
                try {
                    out.close();
                    fileName = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean deleteFile(String path){
        if ("".equals(path) || path == null){
            return false;
        }
        // 重新自定义文件的名称
        try {
            File fo = new File(filePath + path);
            System.out.println(filePath + path);
            if (fo.exists()){
                fo.delete();
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
